package mmc.util;

import java.util.Random;

public class DiffusedRandomMap {
	public final float[][] map;
	public final int resolution;
	
	public DiffusedRandomMap(long seed, int resolution){
		Random r = new java.util.Random(seed);
		
		this.resolution = resolution;
	
		map = new float[resolution][resolution];
		
		for(int i=0;i<resolution;i++){
			for(int j=0;j<resolution;j++){
				map[i][j] = r.nextFloat()+0.5f;
			}
		}
		
		for(int passes = 0;passes<10;passes++){
			for(int i=0;i<resolution;i++){
				for(int j=0;j<resolution;j++){
					map[i][j] = (getWrapped(i-1,j)+getWrapped(i+1,j)+getWrapped(i,j+1)+getWrapped(i,j-1))/4;
				}
			}
		}
	}
	
	private float getWrapped(int idx1, int idx2){
		return map[wrapIndex(idx1)][wrapIndex(idx2)];
	}
	
	private int wrapIndex(int idx){
		return (idx+resolution)%resolution;
	}
	
	public float interpolate(float x, float y, float xMax, float yMax){
		return interpolate(x/xMax, y/yMax);
	}
	
	public float interpolate(float x, float y){
		if(x<0||x>resolution || y<0||y>resolution)
			throw new RuntimeException("out of bounds: "+x+" "+y);
		
		x *= resolution-1;
		y *= resolution-1;
		
		int ix = (int) x;
		int iy = (int) y;
		
		x -= ix;
		y -= iy;
		//System.out.println("ret = "+(y* (x*map[ix][iy] + (1-x)*map[ix+1][iy]) +  (1-y)*(x*map[ix][iy+1] + (1-x)*map[ix+1][iy+1])));
		return y* (x*map[ix][iy] + (1-x)*map[ix+1][iy]) +  (1-y)*(x*map[ix][iy+1] + (1-x)*map[ix+1][iy+1]);
		//System.out.println("returnin "+ix+" "+ix+" "+map[ix][iy]);
		//return map[ix][iy];
	}
}
